package com.linewell.license.demo.security;

import com.linewell.license.demo.utils.CurrentRequestUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* @author
* Company:
* Createtime : 2018年9月18日 下午5:38:28
* Description : 用户未登录时（匿名用户）发生权限异常时的处理类
* *             这里继承了LoginUrlAuthenticationEntryPoint
* *  			就针对ajax访问的情况作了特判
*/
public class RestAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
	private String loginFormUrl;

    public RestAuthenticationEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
        this.loginFormUrl = loginFormUrl;
    }

    @Override
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
        //如果是ajax请求
        if (CurrentRequestUtils.isAjaxRequest(request)) {
        	//告诉ajax这是重定向
        	response.setHeader("REDIRECT", "REDIRECT");
        	//重定向地址
            response.setHeader("CONTEXTPATH", request.getContextPath()+this.loginFormUrl);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            super.commence(request, response, authException);
        }
    }

}
